//
//  OosQuery.m
//  com.oos.kraken
//
//  Created by Pablo Gonzalez on 2/16/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import "OosQuery.h"
#import "../../Utils/NSStringUtils.h"

static NSString *const APP_TOKEN_KEY = @"appToken";
static NSString *const COUNT_KEY = @"count";
static NSString *const PAGE_KEY = @"page";
static NSString *const FIELDS_KEY = @"fields";
static NSString *const ORDER_KEY = @"order";
static NSString *const SINCE_KEY = @"modifiedSince";
static NSString *const ALT_KEY = @"alt";
static NSString *const UUID_KEY = @"uuid";

#define DEVICE_UUID @"DEVICE_UUID"

@implementation OosQuery

+ (OosQuery *) query:(NSURL *)queryURL
{
	//return [super queryWithUrl:queryURL];
	return [[[self alloc] initWithFeedURL:queryURL] autorelease];
}

- (NSString *) appToken
{
	return [self valueForParameterWithName:APP_TOKEN_KEY];
}

- (void) setAppToken:(NSString *)appToken
{
	[self addCustomParameterWithName:APP_TOKEN_KEY value:appToken];
}

/* count */

static int const DEFAULT_COUNT = 10;
static int const DEFAULT_PAGE = 1;
static int const INVALID_VALUE = 0;

- (NSNumber *) count
{
	return [NSNumber numberWithInteger:
			[self intValueForParameterWithName:COUNT_KEY 
						 missingParameterValue:DEFAULT_COUNT]];
}

- (void) setCount:(NSNumber *)count
{
	[self addCustomParameterWithName: COUNT_KEY 
							intValue: [count intValue]
					  removeForValue: INVALID_VALUE];
}

/* page */

- (NSNumber *) page
{
	return [NSNumber numberWithInteger:
			[self intValueForParameterWithName: PAGE_KEY 
						 missingParameterValue: DEFAULT_PAGE]];
}

- (void) setPage:(NSNumber *)page
{
	[self addCustomParameterWithName: PAGE_KEY 
							intValue: [page intValue]
					  removeForValue: INVALID_VALUE];
}

- (void) setFields:(NSString *) fields
{
	[self addCustomParameterWithName:FIELDS_KEY value:fields];
}

- (NSString *) fields
{
	return [self valueForParameterWithName:FIELDS_KEY];
}

- (BOOL) clearFields
{
	[self removeCustomParameterWithName:FIELDS_KEY];
	return [self fields] == nil;
}

- (BOOL) hasField: (NSString *)field
{
	return [NSStringUtils string: self.fields hasValue: field];
}

- (void) addField:(NSString *)field
{
	if (self.fields) {
		self.fields = [NSStringUtils addValue:field toString: self.fields];
	} else {
		self.fields = field;
	}
}

- (void)setOrder:(NSString *)order
{
    [self addCustomParameterWithName:ORDER_KEY 
                               value:order];
}

- (NSString *)order
{
    return [self valueForParameterWithName: ORDER_KEY];
}

static NSDateFormatter *formatter = nil;

- (void) initFormatter
{
    if (!formatter) {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
}

- (void)setSince:(NSDate *)since
{
    NSString *sinceString = nil;
    if (since) {
        [self initFormatter];
        sinceString = [formatter stringFromDate:since];
    }
    [self addCustomParameterWithName:SINCE_KEY 
                               value:sinceString];
}

- (NSDate *)since
{
    NSDate *since = nil;
    NSString *dateString = [self valueForParameterWithName:SINCE_KEY];
    if (dateString) {
        [self initFormatter];
        since = [formatter dateFromString:dateString];
    }
    return since;
}

- (NSString *)alt
{
    return [self valueForParameterWithName:ALT_KEY];
}

- (void)setAlt:(NSString *)alt
{
    
    [self addCustomParameterWithName:ALT_KEY 
                               value:alt];
}

- (NSString *)uuid 
{
    return [self valueForParameterWithName:UUID_KEY];
}

- (void)setUuid:(NSString *)uuid
{
    [self addCustomParameterWithName:UUID_KEY 
                               value:uuid];
}

- (void) removeField:(NSString *)field
{
	if (self.fields) {
		self.fields = [NSStringUtils removeValue:field fromString: self.fields];
	}
}

- (NSString *) restoreOrCreateUuid
{
    NSString *uuid = [[NSUserDefaults standardUserDefaults] valueForKey:DEVICE_UUID];
    if (uuid == nil) {
        // source http://iphonedevelopertips.com/general/create-a-universally-unique-identifier-uuid.html
        
        // Get the string representation of CFUUID object.
        uuid = [(NSString *)CFUUIDCreateString(kCFAllocatorDefault, CFUUIDCreate(kCFAllocatorDefault)) autorelease];
        [[NSUserDefaults standardUserDefaults] setValue:uuid forKey:DEVICE_UUID];
        
    }
    return uuid;
}

- (void) packStore: (OosOptionsStore *) store
{
	// Get paging options
	OosPageOptions *pageOptions = [store pageOptions];
	self.page = [pageOptions page];
	self.count = [pageOptions pageSize];
	
	// Get Field options
	OosFieldOptions *fieldOptions = [store fieldOptions];
	if ([[fieldOptions fields] count] > 0) {
		self.fields = [[fieldOptions fields] componentsJoinedByString:@","];
	} else {
		[self clearFields];
	}
    
    // Query options
    OosQueryOptions *queryOptions = [store queryOptions];
    self.since = queryOptions.since;
    //self.alt = queryOptions.alt;
    
    OosOrderOptions *orderOptions = store.orderOptions;
    if (orderOptions.order) {
        self.order = [orderOptions.order description];
    }
    self.uuid = [self restoreOrCreateUuid];
}

@end
